<template>
  <div class="order-management-container">
    <!-- <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入订单号或客户名称"
        prefix-icon="el-icon-search"
        style="width: 300px; margin-right: 10px;"
      ></el-input>
      <el-button type="primary" @click="fetchOrders">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div> -->

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="orders"
        style="width: 100%"
        :header-cell-style="{ 'background': 'linear-gradient(90deg, #3b82f6 0%, #60a5fa 100%)', 'color': 'white', 'font-weight': 'bold', 'border-radius': '4px 4px 0 0' }"
        :row-style="{ 'transition': 'background-color 0.2s' }"
        :cell-style="{ 'padding': '12px', 'border-radius': '4px' }"
        fit
      >
        <el-table-column prop="orderId" label="订单ID" width="100"></el-table-column>
        <el-table-column prop="orderNumber" label="订单编号" min-width="180"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" min-width="120"></el-table-column>
        <el-table-column prop="couponPrice" label="优惠券价格" min-width="120">
          <template slot-scope="scope">{{ scope.row.couponPrice / 10 }}</template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名称" min-width="120"></el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" min-width="100">
          <template slot-scope="scope">{{ scope.row.totalAmount }}</template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" min-width="140">
          <template slot-scope="scope">
            <span :class="getOrderStatusClass(scope.row.orderStatus || 'UNKNOWN')">
              <i :class="getOrderStatusIcon(scope.row.orderStatus || 'UNKNOWN')"></i>
              <span class="status-text">{{ getOrderStatusText(scope.row.orderStatus || 'UNKNOWN') }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" min-width="180"></el-table-column>
        <el-table-column label="操作" min-width="150">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="viewOrderDetail(scope.row.orderId)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="handleClose"
    >
      <div v-if="orderDetail" class="order-detail">
        <div class="order-basic-info">
          <h3>基本信息</h3>
          <p>订单编号: {{ orderDetail.orderNumber }}</p>
          <p>客户名称: {{ orderDetail.userName }}</p>
          <p>供应商名称: {{ orderDetail.supplierName }}</p>
          <p>优惠券价格: {{ orderDetail.couponPrice / 10}}</p>
          <p>订单金额: {{ orderDetail.totalAmount }}</p>
          <p>订单状态: <span :class="getOrderStatusClass(orderDetail.orderStatus)">{{ getOrderStatusText(orderDetail.orderStatus) }}</span></p>
          <p>创建时间: {{ orderDetail.createdAt }}</p>
        </div>

        <div class="order-items">
          <h3>订单商品</h3>
          <el-table :data="orderDetail.orderItems" style="width: 100%">
            <el-table-column prop="productName" label="商品名称" min-width="200"></el-table-column>
            <el-table-column prop="skuName" label="规格" min-width="150"></el-table-column>
            <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="100"><template slot-scope="scope">{{ scope.row.unitPrice }}</template></el-table-column>
            <el-table-column prop="totalPrice" label="小计" width="100"><template slot-scope="scope">{{ scope.row.totalPrice }}</template></el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrders, getOrderDetail } from '@/api/order'

export default {
  name: 'OrderManagement',
  data() {
    return {
      orders: [],
      orderDetail: null,
      loading: false,
      searchKeyword: '',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false
    }
  },
  mounted() {
    this.fetchOrders()
  },
  methods: {
    fetchOrders() {
      this.loading = true
      console.log('发送的参数:', { pageNum: this.pageNum, pageSize: this.pageSize, keyword: this.searchKeyword });
      getOrders({ pageNum: Number(this.pageNum), pageSize: Number(this.pageSize), keyword: this.searchKeyword }).then(response => {
        // 正确解析后端返回的数据结构
        this.orders = response.data.data.records || []
        // 使用后端返回的total字段
        this.total = response.data.data.total || 0
        this.loading = false
      }).catch(error => {
        this.$message.error('获取订单列表失败: ' + error.message)
        this.loading = false
      })
    },
    getOrderDetail(orderId) {
      this.loading = true
      getOrderDetail(orderId).then(response => {
        // 打印响应数据结构用于调试
        console.log('订单数据响应:', response)
        if (response.data.code === 0) {
          this.orderDetail = response.data.data
          this.dialogVisible = true
        } else {
          this.$message.error('获取订单详情失败: ' + response.msg)
        }
        this.loading = false
      }).catch(error => {
        this.$message.error('获取订单详情失败: ' + error.message)
        this.loading = false
      })
    },
    viewOrderDetail(orderId) {
      this.getOrderDetail(orderId)
    },
    handleOrderAction(order) {
      // 处理订单的逻辑，如发货、取消等
      this.$message.info('处理订单: ' + order.orderId)
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.fetchOrders()
    },
    handleCurrentChange(page) {
      this.pageNum = page
      this.fetchOrders()
    },
    resetSearch() {
      this.searchKeyword = ''
      this.pageNum = 1
      this.fetchOrders()
    },
    handleClose() {
      this.dialogVisible = false
    },
    getOrderStatusText(status) {
      // 根据实际业务逻辑映射状态文本
      const statusMap = {
        'NOT_STARTED': '未开始',
        'PAID': '已支付',
        'WAIT_PAY': '待支付',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消',
        'REFUNDED': '已退款',
        'CLOSED': '已关闭',
        'REFUNDING': '退款中',
        'WAIT_REFUND': '待退款',
        'WAIT_SEND': '待发货',
        'WAIT_RECEIVE': '待收货',
        'WAIT_COMMENT': '待评价',
        'WAIT_CONFIRM': '待确认',
        'WAIT_PAY_AFTER_RECEIVE': '待收货后支付',
        'WAIT_PAY_AFTER_RECEIVE_CONFIRM': '待收货后支付确认',
        'WAIT_PAY_AFTER_RECEIVE_REFUND': '待收货后支付退款',
      }
      return statusMap[status] || '未知状态'
    },
    getOrderStatusClass(status) {
      // 根据实际业务逻辑映射状态样式
      const classMap = {
        'NOT_STARTED': 'status-not-started',
        'PAID': 'status-paid',
        'WAIT_PAY': 'status-wait-pay',
        'COMPLETED': 'status-completed',
        'CANCELLED': 'status-cancelled',
        'REFUNDED': 'status-refunded',
        'CLOSED': 'status-closed',
        'REFUNDING': 'status-refunding',
        'WAIT_REFUND': 'status-wait-refund',
        'WAIT_SEND': 'status-wait-send',
        'WAIT_RECEIVE': 'status-wait-receive',
        'WAIT_COMMENT': 'status-wait-comment',
        'WAIT_CONFIRM': 'status-wait-confirm',
        'WAIT_PAY_AFTER_RECEIVE': 'status-wait-pay-after-receive',
        'WAIT_PAY_AFTER_RECEIVE_CONFIRM': 'status-wait-pay-after-receive-confirm',
        'WAIT_PAY_AFTER_RECEIVE_REFUND': 'status-wait-pay-after-receive-refund',
      }
      return classMap[status] || 'status-unknown'
    },
    getOrderStatusIcon(status) {
      // 为不同状态添加对应的图标
      const iconMap = {
        0: 'el-icon-time',
        1: 'el-icon-sort',
        2: 'el-icon-truck',
        3: 'el-icon-check',
        4: 'el-icon-delete'
      }
      return iconMap[status] || 'el-icon-question'
    }
  },
  filters: {
    formatPrice(price) {
      if (typeof price !== 'number' || isNaN(price)) {
        return '¥0.00'
      }
      return '¥' + (price / 100).toFixed(2)
    },
    formatDate(date) {
      if (!date) return '-'
      const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }
      return new Date(date).toLocaleString('zh-CN', options)
    }
  }
}
</script>

<style scoped>
.order-management-container {
  padding: 20px;
  box-sizing: border-box;
  height: 100%;
}

.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.table-container {
  flex: 1;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.order-detail {
  padding: 10px;
}

.order-basic-info {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.order-items {
  margin-top: 20px;
}

/* 订单状态样式 */
.status-pending {
  color: #ff7d00;
  background-color: #fff8e1;
  padding: 4px 10px;
  border-radius: 16px;
  display: inline-flex;
  align-items: center;
  font-size: 13px;
  transition: all 0.2s ease;
}

.status-pending:hover {
  background-color: #fff1c1;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.status-processing {
  color: #1976d2;
  background-color: #e3f2fd;
  padding: 4px 10px;
  border-radius: 16px;
  display: inline-flex;
  align-items: center;
  font-size: 13px;
  transition: all 0.2s ease;
}

.status-processing:hover {
  background-color: #bbdefb;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.status-shipped {
  color: #00796b;
  background-color: #e0f2f1;
  padding: 4px 10px;
  border-radius: 16px;
  display: inline-flex;
  align-items: center;
  font-size: 13px;
  transition: all 0.2s ease;
}

.status-shipped:hover {
  background-color: #b2dfdb;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.status-completed {
  color: #388e3c;
  background-color: #e8f5e9;
  padding: 4px 10px;
  border-radius: 16px;
  display: inline-flex;
  align-items: center;
  font-size: 13px;
  transition: all 0.2s ease;
}

.status-completed:hover {
  background-color: #c8e6c9;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.status-cancelled {
  color: #757575;
  background-color: #f5f5f5;
  padding: 4px 10px;
  border-radius: 16px;
  display: inline-flex;
  align-items: center;
  font-size: 13px;
  transition: all 0.2s ease;
}

.status-cancelled:hover {
  background-color: #ffcdd2;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.status-unknown {
  color: #757575;
  background-color: #f5f5f5;
  padding: 4px 10px;
  border-radius: 16px;
  display: inline-flex;
  align-items: center;
  font-size: 13px;
  transition: all 0.2s ease;
}

.status-unknown:hover {
  background-color: #eeeeee;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.status-pending i,
.status-processing i,
.status-shipped i,
.status-completed i,
.status-cancelled i,
.status-unknown i {
  margin-right: 6px;
  font-size: 14px;
}

.status-text {
  line-height: 1;
}
</style>